<template>
    <div id="manage">
        <div class="manage_top">
            <div class="form">
                <div style="margin: 15px 20px 0 20px">
                    <zy-select v-if="formConfig" :fromValue="queryForm" :formConfig="formConfig" @search="search" @resetForm="resetForm" :actions="actions"></zy-select>
                </div>
                <div style="height: 40px; display: flex; margin: 10px 20px 0 20px">
                    <div class="table_title">{{ table_title }}管理</div>
                    <div class="btns">
                        <el-button v-for="item in actions" :key="item.label" :icon="item.icon" @click="item.click()">{{ item.label }}</el-button>
                    </div>
                </div>
            </div>
        </div>
        <div class="manage_bottom">
            <div class="table">
                <div class="table_mask"></div>
                <zy-table :loading="loading" :tableData="tableData" :tableColumn="tableColumn" :pageSize="pagination.pageSize" :total="pagination.total" @changePage="changePage" @changeID="changeID"></zy-table>
            </div>
        </div>
        <edit-page ref="editPage" @get="searchBtn"></edit-page>
        <sensor ref="sensor"></sensor>
        <el-dialog title="上传测点" :visible.sync="dialogTableVisible">
            <el-upload ref="upload" action="/api/sensor/upload" :file-list="fileList" :auto-upload="false" accept=".xlsx" :on-success="handSuccess" :on-change="handleChange" :on-progress="handError">
                <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                <el-button style="margin-left: 10px" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
                <el-button size="small" type="primary" @click="download">下载模板</el-button>
                <div slot="tip" class="el-upload__tip">只能上传xlsx文件</div>
            </el-upload>
        </el-dialog>
        <zy-form ref="zyform" :dialog="dialog" @add="add" @set="edit" />
    </div>
</template>

<script>
import { setDeviceGetlistApi, fileApi, deviceGetSensorsApi, requestApi } from '@/requset/api'
import { mapState } from 'vuex'
import { formConfig, column } from './formConfig.js'
import { Loading } from 'element-ui'
import SearchManage from '@/components/basic/SearchManage.vue'
import zyFile from '@/components/common/zyFile.vue'
import editPage from './edit'
import Sensor from './Sensor'
import Vue from 'vue'
export default {
    extends: SearchManage,
    components: { editPage, Sensor, zyFile },
    data() {
        return {
            table_title: '设备',
            url: 'device',
            actions: [
                {
                    label: '导入',
                    icon: 'el-icon-upload2',
                    click: () => {
                        this.dialogTableVisible = true
                    },
                    if: () => this.operate,
                },
                {
                    label: '添加',
                    icon: 'el-icon-folder-add',
                    click: () => {
                        this.handleAdd()
                    },
                    if: () => this.operate,
                },
            ],
            formConfig: formConfig,
            queryForm: {
                page: 1,
                size: 20,
                device_name: null,
                type_id: null,
                scope_id: null,
                scope_id_list: [],
            },
            queryFormC: {
                page: 1,
                size: 20,
                device_name: null,
                type_id: null,
                scope_id: null,
                scope_id_list: [],
            },
            dialogTableVisible: false,
            fileList: [],
            confirmText: '确认删除此条数据?本次操作会清空该设备下所有测点在数据库中的表和数据',
            dialog: {
                labelWidth: '0px',
                config: [
                    {
                        name: 'config',
                        type: 'form',
                        label: '',
                        required: true,
                        baseForm: {},
                        fixed: true,
                        config: [
                            {
                                name: 'name',
                                type: 'input',
                                label: '测点名称',
                            },
                            {
                                name: 'qt',
                                type: 'input',
                                label: '启停速度值（不填不判断启停）',
                            },
                            {
                                name: 'yctem',
                                type: 'input',
                                label: '异常温度值',
                            },
                            {
                                name: 'ycvel',
                                type: 'input',
                                label: '异常速度值',
                            },
                        ],
                    },
                ],
                form: {},
                title: '设备测点配置',
            },
            default_config: {
                qt: '0.3',
                yctem: [-40, 85],
                ycvel: [0, 20],
            },
            device: {},
        }
    },
    methods: {
        handleAdd(id) {
            this.$refs.editPage.doOpen(id)
        },
        submitUpload() {
            if (this.fileList.length === 0) {
                this.$message.error('导入文件不能为空')
                return
            }
            if (this.fileList.length > 1) {
                this.$message.error('一次只能导入一个文件')
                return
            }
            this.$refs.upload.submit()
            this.loadingAll = Loading.service({
                target: 'body',
                background: 'rgb(0,0,0,.4)',
            })
        },
        handleChange(file, fileList) {
            this.fileList = fileList
        },
        handSuccess(res) {
            this.$refs.upload.clearFiles()
            this.fileList = []
            if (res.code === 0) {
                this.$message.success(res.msg)
                this.dialogTableVisible = false
                setTimeout(() => {
                    this.searchBtn()
                }, 200)
            } else {
                this.$message.error((res.msg ? res.msg : '') + '导入失败')
            }
        },
        handError(res) {
            this.loadingAll.close()
        },
        download() {
            fileApi('post', 'device/download', { filename: '测点导入模板.xlsx' }, true).then((res) => {})
        },
        handle1(val) {
            fileApi(
                'post',
                'diag/last/data',
                {
                    device_ids: [val.id],
                    flag: 'zykctest',
                },
                true,
            )
        },

        setDeviceGetlist(obj) {
            setDeviceGetlistApi(obj).then((res) => {
                if (res.data.code == 0) {
                    this.tableData = res.data.data
                    this.pagination = res.data.pagination
                } else {
                    this.$message({
                        type: 'info',
                        message: '网络异常，请稍后重试',
                    })
                    this.tableData = []
                    this.pagination = {}
                }
            })
        },
        add(data) {
            let config = {}
            data.config.map((item) => {
                let { id, qt, yctem, ycvel } = item
                config[id] = {
                    qt: qt.trim(),
                    yctem: JSON.parse(`[${yctem}]`),
                    ycvel: JSON.parse(`[${ycvel}]`),
                }
            })
            this.device.config = JSON.stringify(config)
            requestApi('post', this.url + '/edit', this.device).then((res) => {
                if (res.data.code == 0) {
                    this.$message({
                        type: 'success',
                        message: '编辑成功',
                    })
                    this.searchBtn()
                    this.$refs.zyform.closeDialog()
                }
            })
        },
    },
    computed: {
        ...mapState('backstage', ['backstageData', 'deviceType']),
        tags() {
            if (this.pagination.total !== undefined) {
                return [{ title: '总数', num: this.pagination.total }, null, null, null]
            } else return []
        },
    },
    created() {
        this.formConfig[1].options = this.backstageData
        column[column.length - 1].buttons = [
            {
                text: '查看测点',
                click: (val) => this.$refs.sensor.doOpen(val.id),
                icon: 'el-icon-s-comment',
            },
            {
                text: '编辑',
                click: (val) => this.handleAdd(val.id),
                if: () => this.operate,
                icon: 'el-icon-edit',
            },
            {
                text: '删除',
                click: (val) => this.delete(val),
                if: () => this.operate,
                icon: 'el-icon-delete',
            },
            {
                text: '设备测点配置',
                click: (val) => {
                    this.device = val
                    requestApi('get', 'device/details?id=' + val.id).then((res) => {
                        let configs = []
                        let config = {}
                        res.data.data[0].sensor.map((item) => {
                            config = val.config && item.id in JSON.parse(val.config) ? JSON.parse(val.config)[item.id] : this.default_config
                            config.id = item.id
                            config.name = item.sensor_name
                            configs.push({ ...config })
                        })
                        Vue.set(this.dialog.form, 'config', configs)
                        this.$refs.zyform.openDialog('add')
                    })
                },
                if: () => this.operate,
                icon: 'el-icon-setting',
            },
            {
                text: '导出',
                click: (val) => this.handle1(val),
                icon: 'el-icon-bottom',
            },
        ]
        this.tableColumn = column
        this.searchBtn()
    },
}
</script>
